package com.example.big_orange2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.big_orange2.authorization.annotation.AuthIgnore;
import com.example.big_orange2.authorization.manager.TokenManager;
import com.example.big_orange2.common.Result;
import com.example.big_orange2.entity.Staff;
import com.example.big_orange2.entity.User;
import com.example.big_orange2.entity.code;
import com.example.big_orange2.mapper.UserMapper;

import com.example.big_orange2.service.UserService;
import com.example.big_orange2.service.WeChatService;
import com.example.big_orange2.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private RedisUtils ru;

    @Autowired
    WeChatService weChatService;

    @Resource
    UserMapper userMapper;

    @Resource
    UserService userService;


    //引用公钥
    @Value("${publicKey}")
    private String publicKey;
    //引用私钥
    @Value("${privateKey}")
    private String privateKey;


    @AuthIgnore
    @GetMapping("/getrsa")//占位
    public Result<?> geteRsa() {//?是泛型，表示任意类型
        return Result.success(publicKey);
        //返回公钥
    }

    //微信授权登录获取秘钥
    @AuthIgnore
    @GetMapping(value = "/wechattoken")
    public Result<String> get3rd(@RequestBody code code) {
        Result<String> result = new Result<>();
        try {
            List<String> list = new ArrayList<>();
            list = weChatService.get3rdSession(code.getCode(), "1");
            result.setData(list.get(1));
            result.setResult("success");
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
        return result;
    }

    //依据用户id查询
    @GetMapping("/getdata/{userid}")
    public Result<?> findoneuser(@PathVariable String userid){
        LambdaQueryWrapper<User> wrapper =Wrappers.<User>lambdaQuery();
        wrapper.eq(User::getUserid,userid);//多条件查询
        List<User> Loanhandle = userMapper.selectList(wrapper);//
        return  Result.success(Loanhandle);//返回结果

    }

    //根据获得的秘钥token登录
    @AuthIgnore
    @CrossOrigin
    @GetMapping(value = "/loginState/{token}")
    public Result<Boolean> getLoginState(@PathVariable String token) {
        Result<Boolean> result = new Result<>();
        try {
            Boolean s = weChatService.hasLogin(token);
            result.setData(s);
            result.setResult("success");
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
        return result;
    }

    //退出登录
    @AuthIgnore
    @DeleteMapping(value = "/token")
    public Result<String> logout(String token) {
        Result<String> result = new Result<>();
        try {
            tokenManager.loginOff(token);
            result.setResult("success");

        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
        return result;
    }

    //账号密码登录
    @AuthIgnore
    @PostMapping(value = "/login")
    public Result<String> login(@RequestBody User user) {
        Result<String> result = new Result<>();
        result = userService.login(user);
        return result;
    }

    //注册用户
    @AuthIgnore
    //增
    //向数据库写入（insert）数据的接口
    @PostMapping("/add")
    public Result<?> save(@RequestBody User user) {//?是泛型，表示任意类型
        Result<?> result = new Result<>();
        result = userService.add(user);
        return result;

    }

    //将token和code绑定起来。用户用账号密码登录已经有token了但没有code，现在授权了就把它们绑定在一起
    @AuthIgnore
    @PostMapping(value = "/loginState")
    public Result<Boolean> get3rd(String code, String token) {
        Result<Boolean> result = new Result<>();
        try {
            weChatService.bindCodeAndToken(code, token, "1");
            result.setData(true);
            result.setResult("success");
        } catch (Exception e) {
            result.setData(false);
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
        return result;
    }

    //全部查询
    @GetMapping("/getdata")
    //根据员工号，挑选他负责的客户信息
    public Result<?> finduser() {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        List<User> userdata = userMapper.selectList(wrapper);//
        return Result.success(userdata);//返回结果

    }

//////-------------------------------------------//////////////

    //通过用户的code获取openid 并且判断管理者中是否有对应该用户绑定
    @AuthIgnore
    @PostMapping("/login/wx")
    public Result<?> get3rd_t(@RequestBody code code) {
        Result<?> result = new Result<>();
        result = userService.get3rd(code);
        return result;
    }


    @AuthIgnore
    @PostMapping(value = "/login/pin")
    public Result<?> logind_t(@RequestBody User user) {
        Result<?> result = new Result<>();
        result = userService.logind_t(user);
        return result;

    }

    //注销用户
    @AuthIgnore
    @PutMapping("/update/{userid}")
    //向数据库更新（update）数据的接口
    public Result<?> update(@PathVariable int userid){//是泛型，表示任意类型
        User user=new User();
        user.setUserid(userid);
        user.setActive("1");
        System.out.println(user);
        userMapper.updateById(user);
        return Result.success();
    }
//
//    @PutMapping(value = "/setUserInfo")
//    public Result<?> setUserInfo(@RequestBody User user) {
//        Result<?> result = new Result<>();
//        userMapper.updateById(user);
//        result.setCode("0");
//        result.setMsg("修改成功");
//
//        return result;
//    }

    @PutMapping(value = "/bindWeChat/{code}")
    public Result<?> setStaffOpenid(@RequestBody User user, @PathVariable String code) {
        Result<?> result = new Result<>();
        result = userService.setUserOpenid(user, code);
        return result;
    }
}